const connection = require("../app/database");
const { APP_HOST, APP_PORT } = require("../config/config");

class MomentService {
	// 发布内容
	async create(userId, content) {
		// 将内容存储到数据库
		const statement = `INSERT INTO moment (user_id, content) VALUES(?,?);`;
		const [result] = await connection.execute(statement, [userId, content]);

		// 返回数据
		return result;
	}

	// 获取内容列表
	async getMomentList(offset = 0, size = 10) {
		// 从数据库中查找
		const statement = `SELECT 
                        m.id id, m.content content, m.createAt createTime, m.updateAt updateTime,
                        JSON_OBJECT("id", u.id, "name", u.name, "avatarUrl", u.avatar_url) user,
                        (SELECT COUNT(*) FROM comment c WHERE c.moment_id = m.id) commentCount,
                        (SELECT COUNT(*) FROM moment_label ml WHERE ml.moment_id = m.id) labelCount,
                        (SELECT JSON_ARRAYAGG(CONCAT("${APP_HOST}:${APP_PORT}/moment/images/", file.filename))
												FROM file WHERE m.id = file.moment_id) images
                      FROM moment m
                      LEFT JOIN user u ON m.user_id = u.id
                      LIMIT ?, ?;`;
		const [result] = await connection.execute(statement, [offset, size]);

		// 返回数据
		return result;
	}

	// （复合接口）获取内容详情（内容，作者，评论，评论人）
	async getMomentById(momentId) {
		// 从数据库查找对应详情
		const statement = `SELECT 
                        m.id id, m.content content, m.createAt createTime, m.updateAt updateTime,
                        JSON_OBJECT("id", u.id, "name", u.name, "avatarUrl", u.avatar_url) user,
                        IF(COUNT(l.id), JSON_ARRAYAGG(
                          JSON_OBJECT("id", l.id, "name", l.name)
                        ), NULL) labels,
                        (SELECT IF(COUNT(c.id), JSON_ARRAYAGG(
													JSON_OBJECT("id", c.id, "content", c.content, "commentId", c.comment_id, "createdTime", c.createAt, "updatedTime", c.updateAt,
                              "user", JSON_OBJECT("id", cu.id, "name", cu.name, "avatarUrl", cu.avatar_url))
												), null)
												FROM comment c LEFT JOIN user cu ON c.user_id = cu.id WHERE m.id = c.moment_id) comments,
                        (SELECT JSON_ARRAYAGG(CONCAT("${APP_HOST}:${APP_PORT}/moment/images/", file.filename))
												FROM file WHERE m.id = file.moment_id) images
                      FROM moment m
                      LEFT JOIN user u ON m.user_id = u.id
                      LEFT JOIN moment_label ml ON ml.moment_id = m.id
                      LEFT JOIN label l ON l.id = ml.label_id
                      WHERE m.id = ?
                      GROUP BY m.id;`;
		const [result] = await connection.execute(statement, [momentId]);

		// 返回数据
		return result[0];
	}

	// 修改内容
	async update(content, momentId) {
		const statement = `UPDATE moment SET content = ? WHERE id = ?;`;
		const [result] = await connection.execute(statement, [
			content,
			momentId
		]);

		// 返回数据
		return result;
	}

	// 删除内容
	async remove(momentId) {
		const statement = `DELETE FROM moment WHERE id = ?;`;
		const [result] = await connection.execute(statement, [momentId]);

		// 返回数据
		return result;
	}

	// 标签是否已添加
	async hasLabel(momentId, labelId) {
		const statement = `SELECT * FROM moment_label WHERE moment_id = ? AND label_id = ?;`;
		const [result] = await connection.execute(statement, [
			momentId,
			labelId
		]);

		// 返回数据
		return !!result.length;
	}

	// 添加标签
	async addLabel(momentId, labelId) {
		const statement = `INSERT INTO moment_label (moment_id, label_id) VALUES (?, ?);`;
		const [result] = await connection.execute(statement, [
			momentId,
			labelId
		]);

		// 返回数据
		return result;
	}
}

module.exports = new MomentService();
